import SwiftUI
import SPGlassKit

public struct GlassTabBarExample: GlassExample {
    public static let componentID = "glass-tab-bar"

    enum DemoTab: String, Hashable, Sendable {
        case today, library, inbox, search
    }

    enum DemoRoute: Hashable, Sendable {
        case album(String)
        case track(String)
    }

    @State private var state = GlassTabNavigationState<DemoTab, DemoRoute>(selection: .today)
    @State private var unread = 3
    @State private var showsInbox = true

    /// Deep links of the demo: `glasskit-demo://library/<album>/<track>`.
    static let router = GlassTabRouter<DemoTab, DemoRoute>(
        schemes: ["glasskit-demo"],
        tabs: ["today": .today, "library": .library, "inbox": .inbox, "search": .search]
    ) { tab, components, _ in
        switch (tab, components.count) {
        case (_, 0): []
        case (.library, 1): [.album(components[0])]
        case (.library, 2): [.album(components[0]), .track(components[1])]
        default: nil
        }
    }

    public init() {}

    private var tabs: [GlassTabItem<DemoTab>] {
        var tabs = [
            GlassTabItem(id: DemoTab.today, title: "Today", systemImage: "sun.max"),
            GlassTabItem(id: DemoTab.library, title: "Library", systemImage: "square.stack"),
        ]
        if showsInbox {
            tabs.append(GlassTabItem(id: .inbox, title: "Inbox", systemImage: "tray", badge: .count(unread)))
        }
        tabs.append(GlassTabItem(id: .search, title: "Search", systemImage: "magnifyingglass", isSearch: true))
        return tabs
    }

    public var body: some View {
        GlassTabBar(tabs: tabs, state: $state, minimizeBehavior: .onScrollDown) { tab in
            root(tab)
        } destination: { route in
            switch route {
            case .album(let name):
                List(1...12, id: \.self) { number in
                    NavigationLink("Track \(number)", value: DemoRoute.track("\(name) · \(number)"))
                }
                .navigationTitle(name)
            case .track(let name):
                Text(verbatim: name).font(.title2).navigationTitle("Now playing")
            }
        }
        .onOpenURL { url in
            if let destination = Self.router.destination(for: url) { state.open(destination) }
        }
        .onChange(of: showsInbox) {
            state.reconcile(with: tabs.map(\.id), fallback: .today)
        }
    }

    @ViewBuilder
    private func root(_ tab: DemoTab) -> some View {
        switch tab {
        case .today:
            List {
                Section("Deep links") {
                    Button("Open “Aurora” in Library") {
                        state.open(GlassTabDestination(tab: .library, path: [.album("Aurora")]))
                    }
                    Button("Open track 4 of “Tides”") {
                        if let url = URL(string: "glasskit-demo://library/Tides/4"),
                           let destination = Self.router.destination(for: url) {
                            state.open(destination)
                        }
                    }
                }
                Section("Dynamic tabs") {
                    Toggle("Show the Inbox tab", isOn: $showsInbox)
                    Stepper("Unread: \(unread)", value: $unread, in: 0...99)
                }
            }
            .navigationTitle("Today")
        case .library:
            List(["Aurora", "Tides", "Quiet Hours", "Granite"], id: \.self) { album in
                NavigationLink(album, value: DemoRoute.album(album))
            }
            .navigationTitle("Library")
        case .inbox:
            List(0..<unread, id: \.self) { index in
                Text("Sample message \(index + 1)")
            }
            .overlay {
                if unread == 0 { ContentUnavailableView("No messages", systemImage: "tray") }
            }
            .navigationTitle("Inbox")
        case .search:
            Text("Search results appear here.")
                .foregroundStyle(.secondary)
                .navigationTitle("Search")
        }
    }
}

#Preview("GlassTabBar") { GlassTabBarExample() }
